<template>
    <Toolbar style="border: 2px solid rgb(244, 31, 31)" :editor="editorRef" />
    <Editor style="height: 200px; width: 100%; overflow-y: hidden;  border: 1px solid #ccc"
     @onChange="onChange"
      @onCreated="handleCreated" />
    <!-- <el-button @click="getHtml">点击获取</el-button> -->
</template>
<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { UploadApi } from '@/api';
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
//const valueHtml = ref('<p>hello</p>')

const props = defineProps({
    modelValue: {
        type: String,
        default: ''
    }
})

const emit=defineEmits(['update:modelValue'])

// 模拟 ajax 异步获取内容
onMounted(() => {
    // setTimeout(() => {
    //     valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
    // }, 1500)
 console.log("数据携带：",props.modelValue);
 
})
const onChange = (editor: any) => { 
    console.log("我触发了什么");
    // console.log(editor.getHtml());
    // console.log(editor.children);
    emit('update:modelValue',editor.getHtml())
    
}

const handleCreated = (editor: any) => {
     editorRef.value = editor // 记录 editor 实例，重要！
    editor.getConfig().MENU_CONF['uploadImage'] = {
        // 上传图片的配置
        // 自定义插入图片
         async customUpload(file: File, insertFn: any) {    // TS 语法
            let reader = new FileReader()
            reader.readAsDataURL(file)
            reader.onload = () => {
                UploadApi.upload.call({ name: file.name, base64: reader.result }).then((res:any) => {
                    // 从 res 中找到 url alt href ，然后插入图片
                    insertFn(res, '', '')
                 })
            }          
            // res 即服务端的返回结果

           
        },
    }
}
// const getHtml = () => {
//     console.log("我输入了。。");
//     //console.log("editorRef.value:", editorRef.value.getHtml());

// }

watch(() => props.modelValue, (newValue: any, oldValue: any) => {
   // console.log("我感应到你的操作了。。", newValue);
    editorRef.value.setHtml(newValue)
 })

</script>
<style scoped></style>